package me.itsoo.artemis.framework.core.converter.datetime;

import lombok.extern.slf4j.Slf4j;
import me.itsoo.artemis.framework.core.util.Assert;
import me.itsoo.artemis.framework.core.util.StringUtils;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

/**
 * LocalDateTypeConvertor
 *
 * @author zxy
 * @version 0.0.1
 * @since 2023/5/18
 */
@Slf4j
public class LocalDateTypeConvertor implements ChronoTypeConvertor {

    @Override
    public Object convertIfNecessary(Object value) {
        throw new UnsupportedOperationException("Please take 'convertIfNecessary(java.lang.Object value, java.lang.String format)'");
    }

    @Override
    public Object convertIfNecessary(Object value, String format) {
        if (value == null) {
            return null;
        }

        if (value instanceof LocalDate) {
            return value;
        }

        final String dateTime = value.toString();
        if (StringUtils.isNotBlank(dateTime)) {
            Assert.isTrue(StringUtils.isNotBlank(format), "'format' cannot be empty");

            try {
                final DateTimeFormatter fmt = DateTimeFormatter.ofPattern(format);
                return fmt.parse(dateTime, LocalDate::from);
            } catch (Exception e) {
                log.error("Failed to convert value of type 'java.lang.String' to required type 'java.time.LocalDate'; nested exception is {}: For input string: \"{}\", format: \"{}\"",
                        e.getClass().getName(), value, format, e);
            }
        }

        return null;
    }
}
